package com.wuwei.tms.setting.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwei.tms.pojo.User;
import com.wuwei.tms.utils.result.Result;
import com.wuwei.tms.setting.mapper.UserMapper;
import com.wuwei.tms.setting.service.UserService;
import com.wuwei.tms.utils.MD5Util;
import com.wuwei.tms.utils.token.TokenCache;
import com.wuwei.tms.utils.token.TokenUtil;
import com.wuwei.tms.vo.PasswordVo;
import com.wuwei.tms.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value="/T01/user")
//@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;



    @Resource
    private TokenUtil tokenUtil;



    /**
     * 用户登录后，返回给用户一个token
     * @return
     */
    @PostMapping("login")
    public Result<String> login (@RequestBody User user)

    {
        String password = user.getPassword();
        Long empno = user.getEmpno();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        String md5 = MD5Util.getMD5(password);
        queryWrapper.eq(User::getEmpno,empno).eq(User::getPassword,md5);
        User selectOne = userMapper.selectOne(queryWrapper);
        if (selectOne!=null){
            String token = TokenUtil.generateToken(selectOne.getEmpno());
            // 这里需要将token存放在内存中
            TokenCache.putToken(empno,token);
            return Result.ok(token);
        } else {
            return Result.fail("账号或密码错误!");
        }

    }

    @Value("${prop.user.avatar}")
    private String AVATAR;

    /**
     * 用户通过token，拿到相关信息
     * @return
     */
    @GetMapping("info")
    public Result<User> getUserInfo(@RequestParam("token") String token) {
        // 处理业务逻辑
        Long empno = TokenUtil.getEmpnoFromToken(token);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmpno,empno);
        User user = userMapper.selectOne(queryWrapper);
        int status = user.getStatus();
        UserVo userVo = new UserVo();
        userVo.setAvatar(AVATAR);
        BeanUtils.copyProperties(user,userVo);
        List<String> list = new ArrayList<String>();
        if (1==status) {
            userVo.setIntroduction("I am a super administrator");
            list.add("admin");
            userVo.setRoles(list);
        } else{
            userVo.setIntroduction("I am an editor");
            list.add("editor");
            userVo.setRoles(list);
        }
        return Result.ok(userVo);
    }

    /**
     * 退出登录，这里要销毁本地存储的token
     * @return
     */
    @PostMapping("logout")
    public Result<String> logout (@RequestParam String token){
        Long empno = TokenUtil.getEmpnoFromToken(token);
        TokenCache.removeToken(empno);
        return Result.ok("退出登录成功");
    }

    /**
     * 注册用户，这里只有管理员能注册用户，注册的时候会在拦截器验证一下token，所以不需要做判断，直接注册就可以
     * @return
     */
    @PostMapping("regesiter")
    public Result<String> regesiter (@RequestBody User user){
        Long empno = user.getEmpno();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmpno,empno);
        if (userMapper.selectOne(queryWrapper)!=null) {
            return Result.fail("注册失败！工号重复！");
        }
        //此时要将传进来的密码改为MD5加密的密文
        String md5 = MD5Util.getMD5(user.getPassword());
        user.setPassword(md5);
        userMapper.insert(user);
        return Result.ok("新用户注册成功！");
    }

    /**
     * 修改密码
     * @return
     */
    @PostMapping("setPassword")
    public Result<String> setPassword (@RequestBody PasswordVo passwordVo, HttpServletRequest request) {
        String oldPassword = passwordVo.getOldPassword();
        oldPassword = MD5Util.getMD5(oldPassword);
        String newPassword = passwordVo.getNewPassword();
        newPassword = MD5Util.getMD5(newPassword);
        String token = request.getHeader("Authorization");
        Long empno = TokenUtil.getEmpnoFromToken(token);
        //验证旧密码
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmpno,empno).eq(User::getPassword,oldPassword);
        if (userMapper.selectOne(queryWrapper)!=null) {
            //修改新密码
            User user = new User();
            return  userService.setPassword(user,empno,newPassword);

        } else{
            Result<String> fail = Result.fail("密码修改失败，旧密码错误！");
            fail.setMessage("密码修改失败，旧密码错误！");
            return fail;
        }
    }

    @PutMapping("updateName/{name}")
    public Result<String> updateName(@PathVariable("name")String name, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getEmpnoFromToken(token);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmpno,account);
        User user = userMapper.selectOne(queryWrapper);
        user.setName(name);
        userMapper.updateById(user);
        return Result.ok("修改成功！");

    }

    /**
     * 分页查询用户信息列表
     * @param name
     * @param account
     * @param currentPage
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("list/{name}/{account}/{currentPage}/{pageSize}")
    public Result<List<User>> list(@PathVariable("name") String name,@PathVariable("account") Long account,
                                   @PathVariable("currentPage") Integer currentPage,@PathVariable("pageSize") Integer pageSize,HttpServletRequest request){
        //根据用户的等级来获取不同的用户信息，如果用户是教师，则只能获取学生的用户信息，如果用户是管理员，则可以获取所有人的用户信息
        String token = request.getHeader("Authorization");
        Long account1 = TokenUtil.getEmpnoFromToken(token);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmpno,account1);
        User user = userMapper.selectOne(queryWrapper);
        Integer status = user.getStatus();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        List<User> list = new ArrayList<>();
        if (status==0) {
            return Result.ok(list);
        }
        else {
            wrapper.like(account!=0,User::getEmpno,account).like(!"_".equals(name),User::getName,name);
        }
        IPage<User> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(currentPage);
        IPage<User> userIPage = userMapper.selectPage(page, wrapper);
        list = userIPage.getRecords();
        return Result.ok(list);
    }

    /**
     * 分页查询用户信息列表
     * @param name
     * @param account
     * @param request
     * @return
     */
    @GetMapping("getTotal/{name}/{account}")
    public Result<Long> getTotal(@PathVariable("name") String name,@PathVariable("account") Long account, HttpServletRequest request){
        //根据用户的等级来获取不同的用户信息，如果用户是教师，则只能获取学生的用户信息，如果用户是管理员，则可以获取所有人的用户信息
        String token = request.getHeader("Authorization");
        Long account1 = TokenUtil.getEmpnoFromToken(token);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmpno,account1);
        User user = userMapper.selectOne(queryWrapper);
        Integer status = user.getStatus();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //如果用户状态是0.代表是管理员，如果是1，代表是教师,如果是2，则返回空
        if (status==0) {
            return Result.ok(0L);
        }
        else {
            wrapper.like(account!=0,User::getEmpno,account).like(!"_".equals(name),User::getName,name);
        }
        Long count = userMapper.selectCount(wrapper);
        return Result.ok(count);
    }


    /**
     * 删除用户信息的方法，除了删除user表，还要删除test_answers表和test_result表
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public Result<String> delete(@PathVariable("id")Long id){
        /**
         * id为1的用户信息不允许删除
         */
        if (id==1) {
            return Result.fail("超级管理员不允许删除！");
        }
        Result<String> result = userService.deleteById(id);
        return result;
    }

    @PutMapping("resetPassword/{id}/{password}")
    public Result<String> resetPassword(@PathVariable("id") Long id,@PathVariable("password") String password, HttpServletRequest request){
        if (id==1) {
            return Result.fail("超级管理员密码不允许修改！");
        }
        User user = userMapper.selectById(id);
        String md5 = MD5Util.getMD5(password);
        user.setPassword(md5);
        String token = request.getHeader("Authorization");
        Long account1 = TokenUtil.getEmpnoFromToken(token);
        LocalDateTime now = LocalDateTime.now();
        user.setUpdatedTime(now);
        user.setEditBy(account1);
        userMapper.updateById(user);
        return Result.ok("重置成功！");
    }

    @GetMapping("getName/{empno}")
    public Result<String> getName(@PathVariable("empno") Long empno){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmpno,empno);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null) {
            return Result.fail("员工编号错误！");
        }else {
            return Result.ok(user.getName());
        }
    }

    @PostMapping("update")
    public Result<String> update(@RequestBody User user){
        if (user.getId()==1) {
            return Result.fail("超级管理员权限不得修改！");
        }
        userMapper.updateById(user);
        return Result.ok("更新成功");
    }

//
//    /**
//     * 销毁用户的时候设定超级管理员的账户不可销毁
//     * @param id
//     * @return
//     * @throws SaveException
//     */
//    @RequestMapping("/user/destory.do")
//    @ResponseBody
//    public Object destory (String id) throws SaveException {
//        Message message = new Message();
//        //判断如果是超级管理员，则不能销毁该用户
//        if ("23523545345".equals(id)){//23523545345是ww在t_user表里的主键
//            message.setSuccess(false);
//            message.setMessage("超级管理员账户不可销毁！");
//        }
//        else {
//            message = userService.delete(id);
//        }
//        return message;
//    }
}
